﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraBars;
using LayerEntity.Caja;
using LayerEntity.Sistema;
using System.Collections;
using DevExpress.XtraEditors;
using LayerEntity.Creditos;
using LayerLogic;
namespace System2012.Creditos
{
    public partial class frmVisorAmortizaCuotas : DevExpress.XtraEditors.XtraForm
    {
        private double MONTO_RECIBIDO;
        private int op_fp;
        /// <summary>
        /// TABLA QUE ALMACENA TODOS LOS PAGOS DE LAS CANCELACIONES
        /// </summary>
        DataTable dtbPagos = new DataTable("Pagos");
        double TOTAL_VALES, TOTAL_EFECTIVO, MONTO_VUELTO;
        double MONTO_PAGAR;
        double EQUIVALE_SOLES;
        double TOT_EQUIVALE_SOLES;
        double IMPORTE_MORA;
        double PORCENT_MORA;
        double IMPORTE_COBRAR_CUOTA;
        private double IMPORTE_COBRAR;
        private double MONTO_TOTAL;
        string ID_CUOTA;
        string ID_CREDITO;
        string ID_SUCURSAL;
        int op_descargo;
        /// <summary>
        /// Indica si estamos editanado o creando uno Nuevo
        /// 0: Nuevo Documento
        /// 1: Editando y Guardando
        /// </summary>
        int operacion = 0;
        public frmVisorAmortizaCuotas()
        {
            InitializeComponent();

        }
        public frmVisorAmortizaCuotas(ArrayList data)
        {
            InitializeComponent();
            CabeceraPagos();
            RecControles(this);
           // HabilitarFP();
            if (!this.BGWTipDoc.IsBusy)
            {
                this.BGWTipDoc.RunWorkerAsync();
            }
            this.ItemTarjeta.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            InitEvents();
            op_descargo = int.Parse(data[6].ToString());
            ID_CUOTA = Convert.ToString(data[2]);
            ID_CREDITO = Convert.ToString(data[3]);
            ID_SUCURSAL = Convert.ToString(data[4]);
            MONTO_TOTAL = Convert.ToDouble(data[0]);
            IMPORTE_MORA = Convert.ToDouble(data[5]);
            IMPORTE_COBRAR = Convert.ToDouble(data[1]);
            IMPORTE_COBRAR_CUOTA = Convert.ToDouble(data[1]);
            txtTotalVenta.Text = Convert.ToString(MONTO_TOTAL);
            txtMora.Text =Convert.ToString(IMPORTE_MORA);
            lblImporteCobrar.Text = Convert.ToString(IMPORTE_COBRAR);
            gridControl1.DataSource = dtbPagos;
        }

        #region Registro de Amortizaciones
        private void Grabar()
        {
            ECreditos Ecred = new ECreditos();
            EMovientoCaja Emov = new EMovientoCaja();
            Ecred.IdCuota = ID_CUOTA;
            Ecred.Id_credito = ID_CREDITO;
            Ecred.Id_sucursal_credito = int.Parse(ID_SUCURSAL);
            Emov.Id_movimiento = 0;
            Emov.Serie = txtSerie.Text;
            Emov.Nro_comprobante = txtNroComprobante.Text;
            Emov.Id_caja_destino = int.Parse(txtIdCaja.Text);
            Emov.Doc_referencia = txtNroReferencia.Text;
            Emov.Importe_mora = Convert.ToDouble(txtMora.Text);
            Emov.Imp_movimiento =Convert.ToDouble( txtTotImporte.Text);
            Emov.Glosa = "MOVIENTO DE CAJA POR AORTIZACION DE CUOTA";
            Emov.Desacargo = "N";
            Emov.Imp_recibido = Convert.ToDouble(txtImpRecibido_s.Text);
            Emov.Imp_vuelto = double.Parse(txtTotalVuelto.Text);
            Emov.Idusuario = "";
            Emov.Id_sucursal_mov = 1;
            Emov.Id_cobrador = txtIdCobrador.Text;
            Emov.Id_tranzaccion_mov = "20";
            Emov.Fecha_mov = DateTime.Parse(txtFecha.EditValue.ToString()).Date;
            Emov.Id_estado = 1;
            Emov.Nro_operacion = this.txtNroOperacion.EditValue!= null ? txtNroOperacion.EditValue.ToString() : "";
            Emov.Id_documento_mov = int.Parse(cmbTipDoc.EditValue.ToString());
            object[] Msg = System2012.SystemUtils.RecordManagerCreditos.RegisterAmortizaCuota(Ecred, Emov, this.operacion == 0 ? EnumOperaciones.Insertar :EnumOperaciones.Actualizar);
            switch (Msg[0].ToString())
            {
                case "0": if (!BGWCuotas.IsBusy) BGWCuotas.RunWorkerAsync();
                    XtraMessageBox.Show(this, "PROCESO EFECTUADO CON EXITO", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Information);
                  
                    break;
                case "MF-1": XtraMessageBox.Show(this, "INCONSITENCIA INESPERADA INTENTE NUEVAMENTE", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error); break;
                case "MF-3": XtraMessageBox.Show(this, "SELECCIONE CORRECTAMENTE LA CUOTA PARA REALIZAR ESTE PROCESO", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error); break;
                case "MF-0": XtraMessageBox.Show(this, string.Format("VERIFIQUE QUE EL INGRESO DE DATOS ESTE CORRECTAMENTE\n\n Codigo: {0}",Msg[0]), "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error); break;
                default: XtraMessageBox.Show(this, string.Format("VERIFIQUE QUE EL INGRESO DE DATOS ESTE CORRECTAMENTE\n\n Codigo: {0}", Msg[0]), "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error); break;
            }
        }
        #endregion
        #region Desplazamientos
        private void PresionadoTeclas(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Down)
            {
               

                //desplazamientos en cacelaciones

                if (sender == this.txtIdCaja)
                {
                    this.cmbTipDoc.Focus();
                    this.cmbTipDoc.SelectAll();
                }
               
              
                if (sender == this.cmbTipDoc)
                {
                    this.txtSerie.Focus();
                    this.txtSerie.SelectAll();
                }
                if (sender == this.txtSerie)
                {
                    this.txtNroComprobante.Focus();
                    this.txtNroComprobante.SelectAll();
                }
                if (sender == this.txtNroComprobante)
                {
                    this.txtIdCobrador.Focus();
                    this.txtIdCobrador.SelectAll();
                }

                if (sender == this.txtIdCobrador)
                {
                    this.txtNroReferencia.Focus();
                    this.txtNroReferencia.SelectAll();
                }
                if (sender == this.txtNroReferencia)
                {
                    this.cmdFormaPago.Focus();
                    this.cmdFormaPago.SelectAll();
                }
                

                if (sender == this.txtMora)
                {
                    if (this.ItemBanco.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
                    {
                        this.cmbBanco.Focus();
                        this.cmbBanco.SelectAll();
                    }
                    else
                    {
                        if (this.ItemTarjeta.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
                        {
                            this.cmbTarjeta.Focus();
                            this.cmbTarjeta.SelectAll();
                        }
                        else
                        {
                            if (this.ItemTarjeta.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Never && this.ItemBanco.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Never)
                            {
                                txtImporteCobrar.Focus();
                                txtImporteCobrar.SelectAll();
                            }

                        }
                    }
                }

                if (sender == this.txtNroOperacion)
                {
                    this.txtImporteCobrar.Focus();
                    this.txtImporteCobrar.SelectAll();
                }
                if (sender == this.txtImporteCobrar)
                {
                    this.txtImporteRecibido.Focus();
                    this.txtImporteRecibido.SelectAll();
                }
            }

            if (e.KeyCode == Keys.Right || e.KeyCode == Keys.Enter)
            {
                if (sender == this.cmbTipDoc)
                {
                    this.txtSerie.Focus();
                    this.txtSerie.SelectAll();
                }
                if (sender == this.cmdFormaPago)
                {
                    this.cmbMoneda.Focus();
                    this.cmbMoneda.SelectAll();
                }

                if (sender == this.cmbMoneda)
                {

                    if (this.ItemBanco.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
                    {
                        this.cmbBanco.Focus();
                        this.cmbBanco.SelectAll();
                    }
                    else
                    {
                        if (this.ItemTarjeta.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
                        {
                            this.cmbTarjeta.Focus();
                            this.cmbTarjeta.SelectAll();
                        }
                        else
                        {
                            if (this.ItemTarjeta.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Never && this.ItemBanco.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Never)
                            {
                                txtImporteCobrar.Focus();
                                txtImporteCobrar.SelectAll();
                            }

                        }
                    }
                    //this.txtNroReferencia.Focus();
                    //this.txtNroReferencia.SelectAll();
                }

                if (sender == this.cmbBanco)
                {
                    this.txtNroOperacion.Focus();
                    this.txtNroOperacion.SelectAll();
                }
                if (sender == this.cmbTarjeta)
                {
                    this.txtNroOperacion.Focus();
                    this.txtNroOperacion.SelectAll();
                }
            }
            if (e.KeyCode == Keys.Up)
            {
                

                if (sender == this.txtSerie)
                {
                    this.cmbTipDoc.Focus();
                    this.cmbTipDoc.SelectAll();
                }

                if (sender == this.txtNroComprobante)
                {
                    this.txtSerie.Focus();
                    this.txtSerie.SelectAll();
                }
                

                if (sender == this.txtNroOperacion)
                {
                    if (this.ItemBanco.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
                    {
                        this.cmbBanco.Focus();
                        this.cmbBanco.SelectAll();
                    }
                    else
                    {
                        if (this.ItemTarjeta.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
                        {
                            this.cmbTarjeta.Focus();
                            this.cmbTarjeta.SelectAll();
                        }
                    }
                }

                if (sender == this.txtImporteCobrar)
                {
                    this.txtNroOperacion.Focus();
                    this.txtNroOperacion.SelectAll();
                }
                if (sender == this.txtImporteRecibido)
                {
                    this.txtImporteCobrar.Focus();
                    this.txtImporteCobrar.SelectAll();
                }
            }
            if (e.KeyCode == Keys.Left)
            {
                if (sender == this.cmdFormaPago)
                {
                    this.txtNroReferencia.Focus();
                    this.txtNroReferencia.SelectAll();
                }
                if (sender == this.cmbMoneda)
                {
                    this.cmdFormaPago.Focus();
                    this.cmdFormaPago.SelectAll();
                }

                if (sender == this.cmbBanco)
                {
                    this.txtMora.Focus();
                    this.txtMora.SelectAll();
                }
                if (sender == this.cmbTarjeta)
                {
                    this.txtMora.Focus();
                    this.txtMora.SelectAll();
                }
            }
        }

        public void RecControles(Control control)
        {
            foreach (Control contHijo in control.Controls)
            {
                if (contHijo.HasChildren)
                {
                    this.RecControles(contHijo);
                }
                contHijo.KeyDown += new KeyEventHandler(PresionadoTeclas);
            }
        }

        #endregion
        #region Cabecera
        private void CabeceraPagos()
        {
            this.dtbPagos.Columns.Add(new DataColumn("Forma_pago", typeof(string)));//F/Pago
            this.dtbPagos.Columns.Add(new DataColumn("Banco", typeof(string)));
            this.dtbPagos.Columns.Add(new DataColumn("Tarjeta", typeof(string)));
            this.dtbPagos.Columns.Add(new DataColumn("Nro_Operación", typeof(string)));//Nro/Operación
            this.dtbPagos.Columns.Add(new DataColumn("M", typeof(string)));
            this.dtbPagos.Columns.Add(new DataColumn("Importe", typeof(decimal)));//Importe(S/ | $)
            this.dtbPagos.Columns.Add(new DataColumn("Imp_Recibido", typeof(decimal)));//Imp.Recibido(S/.| $ )
            this.dtbPagos.Columns.Add(new DataColumn("Equivale", typeof(double)));//Equivale(S/.)
            this.dtbPagos.Columns.Add(new DataColumn("Vuelto", typeof(decimal)));//Vuelto(S/.| $)
            this.dtbPagos.Columns.Add(new DataColumn("idMoneda", typeof(int)));
            this.dtbPagos.Columns.Add(new DataColumn("idFormaPago", typeof(int)));
            this.dtbPagos.Columns.Add(new DataColumn("idBanco", typeof(int)));
            this.dtbPagos.Columns.Add(new DataColumn("idTarjeta", typeof(int)));
        }
        #endregion
        #region Busquedas
        private void SeleccionarVendedor()
        {
            Listados.frmListadoPersona f = new Listados.frmListadoPersona();
            f.ShowDialog();
            txtIdCobrador.Text = f.idPer;
            txtCobrador.Text = f.full_name;
        }

        #endregion
        #region Gestion de Plantillas
        public string PLANTILLA;
        public string IMPRESORA;
        private void getPlantilla()
        {
            if (cmbTipDoc.EditValue != null)
            {
                ESistema obj = new ESistema();
                StringBuilder cadena = new StringBuilder();
                cadena.Append("where id_tranzaccion='");
                cadena.Append(20 + "' and ");
                cadena.Append(" id_documento=");
                cadena.Append(cmbTipDoc.EditValue + "");
                obj.Condicion = cadena.ToString();
                DataTable dtb = System2012.SystemUtils.RecordManagerCommonList.GetListaSeriesDocumento(obj);
                if (dtb.Rows.Count > 0)
                {
                    PLANTILLA = dtb.Rows[0]["plantilla"].ToString();
                    IMPRESORA = dtb.Rows[0]["impresora"].ToString();
                    txtSerie.Text = dtb.Rows[0]["serie"].ToString();
                    getCorrelativo();
                }
                else
                {
                    txtSerie.Text = null;
                    PLANTILLA = null;
                    IMPRESORA = null;
                }
            }
        }
        private void getCorrelativo()
        {
            ESeriesDocumento Es = new ESeriesDocumento();
            Es.Id_Tranzaccion = "20";
            Es.Id_Documento = int.Parse(cmbTipDoc.EditValue.ToString());
            Es.Serie = txtSerie.Text;
            Es.Id_Sucursal = 1;
            string correlativo = System2012.SystemUtils.CommonMaintenanceList.getCorrelativo(Es);
            txtNroComprobante.Text = correlativo.PadLeft(7, '0');
        }
        #endregion

        #region Eventos
        private void EditValueChanged(object sender, EventArgs e)
        {
            this.getPlantilla();
        }
        private void KeyPressInit(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                getCorrelativo();
            }
        }

        private void SerieLeave(object sender, EventArgs e)
        {
            string codigo = this.txtSerie.Text;
            while (codigo.Length < 4)
            {
                codigo = string.Format("0{0}", codigo);
            }
            this.txtSerie.Text = codigo;
        }
        private void SerieEnter(object sender, EventArgs e)
        {
            if (this.txtSerie.Text.Length > 0)
            {
                int codigo = int.Parse(this.txtSerie.Text);
                this.txtSerie.Text = string.Format("{0}", codigo);
            }
        }
        private void NroLeave(object sender, EventArgs e)
        {
            string codigo = this.txtNroComprobante.Text;
            while (codigo.Length < 7)
            {
                codigo = string.Format("0{0}", codigo);
            }
            this.txtNroComprobante.Text = codigo;
        }

        private void NroEnter(object sender, EventArgs e)
        {
            if (this.txtNroComprobante.Text.Length > 0)
            {
                int codigo = int.Parse(this.txtNroComprobante.Text);
                this.txtNroComprobante.Text = string.Format("{0}", codigo);
            }
        }
       
        private void InitEvents()
        {
            this.cmbTipDoc.EditValueChanged += new EventHandler(this.EditValueChanged);
            this.cmbTipDoc.KeyPress += new KeyPressEventHandler(this.KeyPressInit);
            txtSerie.Leave += new EventHandler(this.SerieLeave);
            txtSerie.Enter += new EventHandler(this.SerieEnter);
            txtSerie.KeyPress += new KeyPressEventHandler(this.KeyPressInit);
            txtNroComprobante.Leave += new EventHandler(this.NroLeave);
            txtNroComprobante.Enter += new EventHandler(this.NroEnter);
            txtNroComprobante.KeyPress += new KeyPressEventHandler(this.KeyPressInit);
         
        }
        #endregion
        #region OPERACIONES
        double MONTO_AMORTIZA;
        double IMPORTE_PENDIENTE;
        double TOTAL_LISTA = 0.00;
        private void getAmortizacionMov()
        {
            String val_amotiza = null;
            val_amotiza = this.txtImporteCobrar.Text;
            if (string.IsNullOrEmpty(val_amotiza))
            {
                val_amotiza = "0.0";
            }
            MONTO_AMORTIZA = Convert.ToDouble(val_amotiza);
            double total_s = 0.00;
            double total_d = 0.00;
            for (int i = 0; i < dtbPagos.Rows.Count; i++)
            {
                if (dtbPagos.Rows[i]["M"].Equals("$"))
                {
                    total_d += Convert.ToDouble(dtbPagos.Rows[i]["Importe"]);
                }
                else
                {
                    total_s += Convert.ToDouble(dtbPagos.Rows[i]["Importe"]);
                }
            }
            TOTAL_LISTA = total_s + total_d * Convert.ToDouble(this.txtTipoCambio.Caption);
            if (this.cmbMoneda.SelectedText == "$")// ejecutamos si es ua venta en dolares
            {
                EQUIVALE_SOLES = MONTO_AMORTIZA * Convert.ToDouble(this.txtTipoCambio.Caption);
                TOT_EQUIVALE_SOLES = TOTAL_LISTA + EQUIVALE_SOLES;
                IMPORTE_PENDIENTE = IMPORTE_COBRAR - (EQUIVALE_SOLES + TOTAL_LISTA);
                if (this.TOT_EQUIVALE_SOLES > double.Parse(this.lblImporteCobrar.Text))
                {
                    this.txtImporteCobrar.SelectAll();
                    XtraMessageBox.Show(this, "EL IMP.AMORTIZADO \n NO PUEDE SER MAYOR QUE EL \nIMPORTE A TOTAL PAGAR  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                   
                }
            }
            else
            {
                EQUIVALE_SOLES = MONTO_AMORTIZA;
                IMPORTE_PENDIENTE = IMPORTE_COBRAR - (EQUIVALE_SOLES + TOTAL_LISTA);
                TOT_EQUIVALE_SOLES = TOTAL_LISTA + EQUIVALE_SOLES;
                if (this.TOT_EQUIVALE_SOLES > double.Parse(this.lblImporteCobrar.Text))
                {
                    this.txtImporteCobrar.SelectAll();
                    XtraMessageBox.Show(this, "EL IMP.AMORTIZADO \n NO PUEDE SER MAYOR QUE EL \nIMPORTE A TOTAL PAGAR  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                   
                }
                
            }
            StringBuilder cadena = new StringBuilder();
            cadena.AppendFormat(this.cmbMoneda.SelectedText + " {0} ", this.txtImporteCobrar.Text);
            cadena.AppendFormat("  Equivale en S/. : {0}", this.EQUIVALE_SOLES);
            this.lblMsg.Text = string.Format("PENDIENTE : {0}", this.IMPORTE_PENDIENTE);
            this.lblEquiVale.Text = cadena.ToString();// cmbMoneda.SelectedText + "  " + txtImporteCobrar.Text + "  ||  Equivale en S/. : " + EQUIVALE_SOLES;
     
        }
        private void getImporteVuelto()
        {
            if (this.txtImporteCobrar.Text.Length > 0)
            {
                MONTO_RECIBIDO = Convert.ToDouble(txtImporteRecibido.Text);
                MONTO_PAGAR = Convert.ToDouble(txtImporteCobrar.Text);
                if (MONTO_PAGAR > 0)
                {
                    if (TOT_EQUIVALE_SOLES > IMPORTE_COBRAR)
                    {
                        XtraMessageBox.Show(this, "EL MONTO AMORTIZADO\n"
                                + "NO PUEDE SER MAYOR QUE EL \n"
                                + "IMPORTE A TOTAL PAGAR ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtImporteCobrar.Text="0.00";
                    }
                    if (this.cmbMoneda.SelectedText == "$")// ejecutamos si es ua venta en dolares
                    {
                        MONTO_VUELTO = MONTO_PAGAR - MONTO_RECIBIDO;
                    }
                    else
                    {
                        MONTO_VUELTO = MONTO_PAGAR - MONTO_RECIBIDO;
                    }
                    txtMontoVuelto.Text = MONTO_VUELTO.ToString();
                }
                else
                {
                    if (this.MONTO_RECIBIDO > 0)
                    {
                        XtraMessageBox.Show(this, "Ingrese el Monto del Importe a Cobrar  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        //return;
                    }
                }
            }
            else
            {
                XtraMessageBox.Show(this, "Ingrese el Importe a Cobrar ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.txtImporteCobrar.Focus();
            }
        }
        private void AddDetallePagos()
        {
            double vuelto = double.Parse(this.txtMontoVuelto.Text);
            String val_vuelto = "0.00";
            object idBanco;
            object idTarjeta;
            if (vuelto < 0)
            {
                val_vuelto = this.txtMontoVuelto.Text;
            }
            else
            {
                val_vuelto = "0.00";
            }
            String banco = "";
            if (this.ItemBanco.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
            {
                banco = this.cmbBanco.Text;
                idBanco = this.cmbBanco.EditValue.ToString();
            }
            else
            {
                banco = "";
                idBanco = DBNull.Value;
            }
            String tarjeta = "";
            if (this.ItemTarjeta.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
            {
                tarjeta = this.cmbTarjeta.Text;
                Console.Write(string.Format("TAREJATA :{0}", tarjeta));
                idTarjeta = this.cmbTarjeta.EditValue.ToString();
            }
            else
            {
                idTarjeta = DBNull.Value;// DBNull.Value.ToString();
                tarjeta = "";
            }

            DataRow r = this.dtbPagos.NewRow();
            r["Forma_pago"] = this.cmdFormaPago.Text;
            r["Banco"] = banco;
            r["Tarjeta"] = tarjeta;
            r["Nro_Operación"] = this.txtNroOperacion.EditValue!=null?txtNroOperacion.EditValue:"";
            r["M"] = this.cmbMoneda.Text;
            r["Importe"] = this.txtImporteCobrar.Text;
            r["Imp_Recibido"] = this.txtImporteRecibido.Text;
            r["Equivale"] = this.EQUIVALE_SOLES;
            r["Vuelto"] = val_vuelto;
            r["idMoneda"] = this.cmbMoneda.EditValue;
            r["idFormaPago"] = this.cmdFormaPago.EditValue;
            r["idBanco"] = idBanco;
            r["idTarjeta"] = idTarjeta;
            this.dtbPagos.Rows.Add(r);
        }
        double IMPORTE_TOTAL = 0.00;
        double IMPORTE_TOTAL_VUELTO = 0.00;
        double IMPORTE_TOTAL_RECIBIDO = 0.00;
        private void Totales()
        {
            double importe_s = 0.00;
            double importe_d = 0.00;
            double imp_recibido_s = 0.00;
            double imp_recibido_d = 0.00;
            double imp_vuelto_s = 0.00;
            double imp_vuelto_d = 0.00;

            for (int i = 0; i < this.dtbPagos.Rows.Count; i++)
            {
                if (dtbPagos.Rows[i]["M"].ToString() == "$")
                {
                    imp_recibido_d += double.Parse(this.dtbPagos.Rows[i]["Imp_Recibido"].ToString());
                    importe_d += double.Parse(this.dtbPagos.Rows[i]["Importe"].ToString());
                    imp_vuelto_d += double.Parse(this.dtbPagos.Rows[i]["Vuelto"].ToString());
                }
                else
                {
                    imp_recibido_s += double.Parse(this.dtbPagos.Rows[i]["Imp_Recibido"].ToString());
                    importe_s += double.Parse(this.dtbPagos.Rows[i]["Importe"].ToString());
                    imp_vuelto_s += double.Parse(this.dtbPagos.Rows[i]["Vuelto"].ToString());
                }
            }
            IMPORTE_TOTAL_RECIBIDO = imp_recibido_s + imp_recibido_d * double.Parse(this.txtTipoCambio.Caption);
            IMPORTE_TOTAL_VUELTO = imp_vuelto_s + imp_vuelto_d * double.Parse(this.txtTipoCambio.Caption);
            IMPORTE_TOTAL = importe_s + importe_d * double.Parse(this.txtTipoCambio.Caption);

            this.txtTotImporte.Text = IMPORTE_TOTAL.ToString();
            this.txtImpRecibido_s.Text = IMPORTE_TOTAL_RECIBIDO.ToString();
            // txtImpRecibido_d.setText(format.FormatMoney(String.valueOf(imp_recibido_d)));
            this.txtTotalVuelto.Text = IMPORTE_TOTAL_VUELTO.ToString();
        }
        #endregion

        #region Validaciones

        private bool ValidadcionesMovContado()
        {
            bool res = false;
            if (txtIdCaja.Text == string.Empty)
            {
                res = false;
                XtraMessageBox.Show(this, "No ha seleccionado ninguna caja destino ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtIdCaja.Focus();
            }
            else
            {
                if (txtSerie.Text == string.Empty)
                {
                    res = false;
                    XtraMessageBox.Show(this, "La serie del comprobante no ha sido generada  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtSerie.Focus();

                }
                else
                {
                    if (txtNroComprobante.Text == string.Empty)
                    {
                        res = false;
                        XtraMessageBox.Show(this, "Nro de comprobante no ha sido generado  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtNroComprobante.Focus();

                    }
                    else
                    {
                        if (this.txtTotImporte.Text == string.Empty)
                        {
                            res = false;
                            XtraMessageBox.Show(this, "El importe TOTAL esta vacio  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                        }
                        else
                        {
                            if (this.txtMontoVuelto.Text == string.Empty)
                            {
                                res = false;
                                XtraMessageBox.Show(this, "Ingrese el monto recibido ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                            }
                            else
                            {

                                if (double.Parse(txtTotImporte.Text) < double.Parse(lblImporteCobrar.Text))
                                {
                                    res = false;
                                    XtraMessageBox.Show(this, "OPERACION INCORRECTA \n\n"
                                            + "EL MONTO CANCELADO ES MENOR AL IMPORTE TOTAL A PAGAR", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Warning);


                                }
                                else
                                {

                                    res = true;

                                }

                            }
                        }
                    }
                }
            }
            return res;
        }
        private bool ValidarNroComprobante()
        {
            bool res = false;
            if (this.txtSerie.Text != string.Empty && this.txtNroComprobante.Text != string.Empty)
            {
                if (int.Parse(this.txtSerie.Text) == 0)
                {
                    res = false;
                    this.txtSerie.Focus();
                }
                else
                {
                    if (int.Parse(this.txtNroComprobante.Text) == 0)
                    {
                        res = false;
                        this.txtNroComprobante.Focus();
                    }
                    else
                    {
                        res = true;
                    }
                }
            }
            else
            {
                this.txtSerie.Focus();
                res = false;
            }
            return res;
        }
        private bool ValidaSelects()
        {
            bool res = false;
            if (this.ItemBanco.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
            {
                if (this.cmbBanco.ItemIndex == -1)
                {
                    res = false;
                    XtraMessageBox.Show(this, "NO HA SELECCIONADO NINGUN BANCO\nPARA REALIZAR ESTA OPERACION", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    this.cmbBanco.Focus();
                }
                else
                {
                    res = true;
                }
            }
            else
            {
                if (this.ItemTarjeta.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
                {
                    if (this.cmbTarjeta.ItemIndex == -1)
                    {
                        res = false;
                        XtraMessageBox.Show(this, "NO HA SELECCIONADO\nNINGUNA TARJETA DE PAGO", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);

                        this.cmbTarjeta.Focus();
                    }
                    else
                    {
                        res = true;
                    }
                }
                else
                {
                    if (this.cmbMoneda.ItemIndex == -1)
                    {
                        res = false;
                        XtraMessageBox.Show(this, "SELECCIONE EL TIPO DE MONEDA", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.cmbMoneda.Focus();
                    }
                    else
                    {
                        if (this.ItemTarjeta.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Never && this.ItemBanco.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Never)
                        {
                            res = true;
                        }
                        else
                        {
                            res = false;
                        }
                    }
                }
            }

            return res;
        }
        private bool validacionescajas()
        {
            bool res = false;
            if (this.txtSerie.Text == string.Empty)
            {
                XtraMessageBox.Show(this, "La serie del comprobante no ha sido generada  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                res = false;
            }
            else
            {
                if (this.txtNroComprobante.Text == string.Empty)
                {
                    XtraMessageBox.Show(this, "ro de comprobante no ha sido generado   ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    res = false;
                }
                else
                {
                    if (this.txtImporteCobrar.Text == string.Empty)
                    {
                        res = false;
                        XtraMessageBox.Show(this, "El importe a cobrar esta vacio ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        if (this.txtMontoVuelto.Text == string.Empty)
                        {
                            res = false;
                            XtraMessageBox.Show(this, "Ingrese el monto recibido  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);

                            this.txtImporteRecibido.Focus();
                        }
                        else
                        {
                            if (MONTO_TOTAL == 0 && double.Parse(this.lblImporteCobrar.Text) > 0)
                            {
                                res = false;
                                XtraMessageBox.Show(this, "No se puede realizar esta operacion\n el monto total de la venta es cero ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                if (this.MONTO_VUELTO > 0)
                                {
                                    XtraMessageBox.Show(this, "el valor del vuelto no pude ser mayor a cero, \nverifique este corretamente ingresado  el importe recibido", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);

                                    res = false;
                                }
                                else
                                {
                                    if (this.txtImporteCobrar.Text.Length == 0)
                                    {
                                        res = false;
                                        XtraMessageBox.Show(this, "Ingrese el importe a cobrar", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                    else
                                    {
                                        if (double.Parse(this.txtImporteCobrar.Text) <= 0)
                                        {
                                            res = false;
                                            XtraMessageBox.Show(this, "Ingrese el importe a cobrar  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        }
                                        else
                                        {
                                            if (this.txtImporteRecibido.Text.Length == 0)
                                            {
                                                res = false;
                                                XtraMessageBox.Show(this, "Ingrese el importe a recibido  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                            }
                                            else
                                            {
                                                if (double.Parse(this.txtImporteRecibido.Text) <= 0)
                                                {
                                                    res = false;
                                                    XtraMessageBox.Show(this, "Ingrese el importe recibido  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                }
                                                else
                                                {
                                                    if (this.cmbMoneda.ItemIndex == -1)
                                                    {
                                                        res = false;
                                                        XtraMessageBox.Show(this, "SELECCIONE EL TIPO DE MONEDA", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                        this.cmbMoneda.Focus();
                                                    }
                                                    else
                                                    {
                                                        if (this.cmdFormaPago.ItemIndex == -1)
                                                        {
                                                            res = false;
                                                            XtraMessageBox.Show(this, "SELECCIONE EL TIPO DE MONEDA", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                            this.cmdFormaPago.Focus();
                                                        }
                                                        else
                                                        {
                                                            res = true;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                //res=true;
                            }
                        }
                    }
                }
            }

            return res;
        }
        private bool validaPagos()
        {
            bool res = false;
            if (this.op_fp == 1)
            {
                if (this.txtNroOperacion.Text == string.Empty)
                {
                    res = false;
                    this.txtNroOperacion.Focus();
                    this.lblMsg.Text = "INGRESE EL NRO DE CHEQUE";
                }
                else
                {
                    res = true;
                    this.lblMsg.Text = "";
                }
            }
            else
            {
                if (this.op_fp == 2)
                {
                    if (this.txtNroOperacion.Text == string.Empty)
                    {
                        res = false;
                        this.txtNroOperacion.Focus();
                        this.lblMsg.Text = "INGRESE EL NRO DE OPERACIÓN";
                    }
                    else
                    {
                        res = true;
                        this.lblMsg.Text = "";
                    }
                }
                else
                {
                    if (this.op_fp == 4)
                    {
                        if (this.txtNroOperacion.Text == string.Empty)
                        {
                            res = false;
                            this.txtNroOperacion.Focus();
                            this.lblMsg.Text = ("INGRESE EL NRO DE OPERACIÓN");
                        }
                        else
                        {
                            res = true;
                            this.lblMsg.Text = ("");
                        }
                    }
                    else
                    {
                        if (this.MONTO_VUELTO > 0)
                        {
                            // XtraMessageBox.Show(this, "EL IMP.AMORTIZADO \n NO PUEDE SER MAYOR QUE EL \nIMPORTE A TOTAL PAGAR  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            XtraMessageBox.Show(this, "el valor del vuelto no pude ser mayor a cero, \nverifique este corretamente ingresado  el importe recibido",
                                "Información", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            res = false;
                        }
                        else
                        {
                            res = true;
                        }
                    }
                }
            }
            return res;
        }

        #endregion
     
        private void HabilitarFP()
        {
            // cmbBanco.Properties.Columns.Clear();
            int IDFP = int.Parse(this.cmdFormaPago.EditValue.ToString());
            switch (IDFP)
            {
                case 7: //CHEQUE
                    this.ItemBanco.Size = new System.Drawing.Size(337, 24);
                    this.ItemBanco.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    this.ItemTarjeta.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    this.ItemNroOperacion.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;

                    this.cmbBanco.Enabled = true;
                    this.ItemBanco.Text = "Banco";
                    this.txtNroOperacion.Enabled = true;
                    this.op_fp = 1;
                    if (this.BGWBanco.IsBusy)
                    {
                        this.BGWBanco.RunWorkerAsync();
                    }
                    break;
                case 1: //DEPOSITO
                    this.ItemBanco.Size = new System.Drawing.Size(337, 24);
                    this.ItemBanco.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    this.ItemTarjeta.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    this.ItemNroOperacion.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    this.cmbBanco.Enabled = true;
                    this.ItemBanco.Text = "Banco";
                    this.txtNroOperacion.Enabled = true;
                    if (this.BGWBanco.IsBusy)
                    {
                        this.BGWBanco.RunWorkerAsync();
                    }

                    this.op_fp = 2;
                    break;
                case 8: //EFECTIVO
                    this.ItemBanco.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    this.ItemTarjeta.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    // ItemTarjeta.Size = new System.Drawing.Size(282, 24);
                    this.ItemNroOperacion.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    // this.cmbBanco.Enabled = false;
                    this.ItemBanco.Text = "Caja";
                    this.txtNroOperacion.Enabled = false;
                    this.op_fp = 3;
                    if (this.BGWBanco.IsBusy)
                    {
                        this.BGWBanco.RunWorkerAsync();
                    }
                    //  cmbBanco.Properties.ValueMember = "id_caja";
                    //  cmbBanco.Properties.DisplayMember = "nombre";
                    break;

                case 6: //TARJETA DE CREDITO
                    // layoutControlItem10.Location = new Point(-100, -500);
                    this.ItemBanco.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    this.ItemTarjeta.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    this.ItemNroOperacion.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    this.ItemTarjeta.Size = new System.Drawing.Size(337, 24);
                    this.cmbBanco.Enabled = true;
                    this.ItemBanco.Text = "Tarjeta";
                    this.txtNroOperacion.Enabled = true;
                    if (this.BGWTarjetaCredito.IsBusy)
                    {
                        this.BGWTarjetaCredito.RunWorkerAsync();
                    }

                    break;
                case 5: //TARJETA DE DEBITO

                    this.ItemTarjeta.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    this.ItemBanco.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    this.ItemNroOperacion.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    this.ItemTarjeta.Size = new System.Drawing.Size(337, 24);
                    this.cmbBanco.Enabled = true;
                    this.ItemBanco.Text = "Tarjeta";
                    this.txtNroOperacion.Enabled = true;
                    if (this.BGWTarjetaCredito.IsBusy)
                    {
                        this.BGWTarjetaCredito.RunWorkerAsync();
                    }

                    this.op_fp = 4;
                    break;
                default:
                    this.op_fp = 5;
                    break;
            }
        }

        private void BGWMoneda_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = System2012.SystemUtils.RecordManagerCommonList.GetMoneda();
        }

        private void BGWFormaPago_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = System2012.SystemUtils.RecordManagerCommonList.GetFormaPago("S");
        }

        private void BGWBanco_DoWork(object sender, DoWorkEventArgs e)
        {
            ECaja objC = new ECaja();
            objC.Condicion = "";
            e.Result = System2012.SystemUtils.RecordmanagerCaja.GetListaCaja(objC);
        }

        private void BGWTarjetaCredito_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = System2012.SystemUtils.RecordManagerCommonList.GetTarjetaCredito();
        }

        private void BGWListPersonal_DoWork(object sender, DoWorkEventArgs e)
        {
            ESistema obj = new ESistema();
            StringBuilder cadena = new StringBuilder();
            cadena.Append("where id_persona= ");
            cadena.Append("'");
            cadena.Append(txtIdCobrador.Text + "'");
            obj.Condicion = cadena.ToString();
            e.Result = System2012.SystemUtils.RecordManagerCommonList.GetListadoPersonal(obj);
        }

        private void BGEListCaja_DoWork(object sender, DoWorkEventArgs e)
        {
            ECaja objC = new ECaja();
            objC.Condicion = string.Format("where id_caja = {0}", txtIdCaja.Text);
            e.Result = System2012.SystemUtils.RecordmanagerCaja.GetListaCaja(objC);
        }

        private void BGWTipDoc_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = System2012.SystemUtils.RecordManagerCommonList.GetDocument(2);
        }

        private void BGWMoneda_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.cmbMoneda.Properties.DataSource = e.Result;
            if (!this.BGWBanco.IsBusy)
            {
                cmbMoneda.EditValue = 1;
                this.BGWBanco.RunWorkerAsync();
            }
        }

        private void BGWFormaPago_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.cmdFormaPago.Properties.DataSource = e.Result;
            if (!this.BGWMoneda.IsBusy)
            {
                this.BGWMoneda.RunWorkerAsync();
                cmdFormaPago.EditValue = 8;
            }
        }

        private void BGWBanco_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.cmbBanco.Properties.DataSource = e.Result;
            if (!this.BGWTarjetaCredito.IsBusy)
            {
                this.BGWTarjetaCredito.RunWorkerAsync();
            }
        }

        private void BGWTarjetaCredito_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.cmbTarjeta.Properties.DataSource = e.Result;
        }

        private void BGWListPersonal_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            DataTable dtbPersonal = (DataTable)e.Result;
            if (dtbPersonal.Rows.Count > 0)
            {
                txtCobrador.Text = dtbPersonal.Rows[0]["fullname_persona"].ToString();
            }
            else
            {
                SeleccionarVendedor();
            }
        }

        private void BGEListCaja_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            DataTable dtbC = (DataTable)e.Result;
            if (dtbC.Rows.Count > 0)
            {
                txtCaja.Text = dtbC.Rows[0]["nombre"].ToString();
            }
        }

        private void BGWTipDoc_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.cmbTipDoc.Properties.DataSource = e.Result;
            if (!this.BGWFormaPago.IsBusy)
            {
                
                    cmbTipDoc.EditValue = 24;//movi

                    if (!BGWFormaPago.IsBusy) BGWFormaPago.RunWorkerAsync();

            }
        }

        private void cmdFormaPago_EditValueChanged(object sender, EventArgs e)
        {
            this.HabilitarFP();
        }

        private void txtIdCaja_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (!string.IsNullOrEmpty(this.txtIdCaja.Text))
                {
                    if (!BGEListCaja.IsBusy) BGEListCaja.RunWorkerAsync();
                }
                else
                {
                    //SeleccionarVendedor();
                }
            }
        }

        private void txtIdCobrador_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (!string.IsNullOrEmpty(this.txtIdCobrador.Text))
                {
                    if (!BGWListPersonal.IsBusy) BGWListPersonal.RunWorkerAsync();
                }
                else
                {
                    SeleccionarVendedor();
                }
            }
        }

        private void txtIdCobrador_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F1)
            {
                this.SeleccionarVendedor();
            }
        }


        private void cmbTipDoc_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Left || e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
            {
                getPlantilla();
            }
        }

        private void txtSerie_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                getCorrelativo();
            }
        }

        private void txtImporteCobrar_EditValueChanged(object sender, EventArgs e)
        {
            getAmortizacionMov();
        }

        private void txtImporteRecibido_EditValueChanged(object sender, EventArgs e)
        {
            getImporteVuelto();
        }

        private void txtImporteRecibido_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (this.validaPagos() == true)
                {
                    if (this.txtImporteCobrar.Text != string.Empty)
                    {
                        if (this.validacionescajas() == true)
                        {
                            if (this.ValidaSelects() == true)
                            {
                                this.AddDetallePagos();
                                this.txtImporteCobrar.Text = "0.0";
                                this.txtImporteRecibido.Text = "0.0";
                                this.Totales();
                                if (this.IMPORTE_COBRAR > 0)
                                {
                                    this.cmdFormaPago.Focus();
                                }
                            }
                        }
                    }
                }
            }
        }

        private void btnGrabar_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (ValidadcionesMovContado() == true)
            {
                if (ValidarNroComprobante())
                {
                    if (XtraMessageBox.Show(this, "Está a punto de confirmar el Movimiento de caja\n" +
                                   "Confirmación Requerida ?", "Confirmación", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        Grabar();
                     
                        this.Close();
                    }
                   
                }
            }
        }

        private void frmVisorAmortizaCuotas_Load(object sender, EventArgs e)
        {

        }

        private void BGWCuotas_DoWork(object sender, DoWorkEventArgs e)
        {
            ESistema obj = new ESistema();
            obj.Condicion = "";
            e.Result = System2012.SystemUtils.RecordManagerCreditos.getCuotasPorCobrar(obj);
        }
    }
}